import axios from 'axios'
import { getPolicy } from "@/api/upload";
import year from "../components/Crontab/year";
import month from "../components/Crontab/month";

// 生成唯一值函数
function guid() {
  return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
    let r = Math.random() * 16 | 0,
      v = c == 'x' ? r : (r & 0x3 | 0x8);
    return v.toString(16);
  });
}

function newDate() {
  let date = new Date()
  let year = date.getFullYear()
  let month = date.getMonth()+1
  let day = date.getDate()
  return { year, month, day, key: `${year}/${month}/${day}/` }
}

/**
 * @description: 文件附件上传
 * file： 文件raw对象
 * successCallback： 成功的回调函数
 * errCallBack： 错误的回调函数
 */
const upload = function(file, successCallback = new Function(), errCallBack = new Function()) {
  // let fileName = file.name
  getPolicy().then(res => {
    // 获取文件后缀
    let fileSuffix = file.name.split('.')[1] ? file.name.split('.')[1] : ''
    // 拿到签名信息后，组装表单数据，作参考，具体的字段找后台要
    let obj = res.data
    let config = {}
    config.host = obj['host']
    config.accessid = obj['accessid']
    config.signature = obj['signature']
    config.expire = parseInt(obj['expire'])
    config.policy = obj['policy']
    let fd = new FormData()
    let key = newDate().key
    let filename = guid() +  Date.parse(new Date()) + `.${fileSuffix}`
    let path = key + filename
    console.log(path)
    fd.append('key', path)
    fd.append('OSSAccessKeyId', config.accessid)
    fd.append('policy', config.policy)
    fd.append('signature', config.signature)
    fd.append('success_action_status', '200')
    fd.append('file', file)
    if (config.host.indexOf('http:') > -1) {
      let protocol = window.location.protocol || 'http:'
      let subUrl = config.host.substring(5, config.host.length)
      config.host = protocol + subUrl
    }
    // 数据组装完成后，发送上传请求到阿里云oss
    axios({
      url: config.host,
      method: 'POST',
      data: fd,
    })
      .then(() => {
        // 拿到结果后，做其他操作
        let size = file.size > 1000000 ? parseFloat(file.size / 1000000).toFixed(2) + 'M' : parseFloat(file.size / 1000).toFixed(2) + 'KB'
        successCallback({
          path: path,
          size: size,
          host: config.host
        })
      })
  })
}
export default upload

